package pilgun.Multithread.ThreadPool;

import java.util.ArrayDeque;
import java.util.List;
import java.util.Queue;

public class ThreadPool{
	private final int len;
	private boolean resume = true; 
	private Queue<Runnable> taskList = new ArrayDeque<Runnable>();
	
	public class MyThread extends Thread{
		
		
		public void run(){
			while(true){
				Runnable e = getRunnable();
				if (e == null){
					break;
				}
				e.run();
			}
		}
	}
	
	
	public ThreadPool(int len) {
		this.len = len;
		for (int i = 0; i<len; i++){
			new MyThread().start();
		}
		
	}
	
	public synchronized Runnable getRunnable(){
		while((taskList.peek() == null)&&resume){
			try {
				wait();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		}
		if (taskList.peek() == null){
			return null;
		}
		else{
			return taskList.poll();
		}
		
	}
	
	public synchronized void shutdown(){
		resume = false;
		notifyAll();
	}
	
	public synchronized boolean isShutdown() {
		return !resume;
	}

	public int getLen() {
		return len;
	}

	public synchronized void submit(Runnable task){
		if (!resume){
			return;
		}
		taskList.add(task);
		notifyAll();
	}
	
	public synchronized void submitAll(List<Runnable> tasks){
		if (!resume){
			return;
		}
		taskList.addAll(tasks);
		notifyAll();
	}
	
}